package com.ohuang.util_a.task;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 链式任务
 */
public class LinkTask extends Task{

    private List<Task> tasks;
    //任务超时时间
    private long timeOut=0;

    public LinkTask(List<Task> tasks) {
        this.tasks = tasks;
    }

    public LinkTask(List<Task> tasks, long timeOut) {
        this(tasks);
        this.timeOut = timeOut;
    }

    @Override
    public void run(TaskCallBack taskCallBack) {
        TaskCallBack taskCallBack1 = new OnceTaskCallBack() {
            @Override
            public void onCall() {
                TaskRunUtil.stopTasks(tasks);
                taskCallBack.onNext();

            }
        };
        if (timeOut>0) {
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    taskCallBack1.onNext();
                }
            },timeOut);
        }
        TaskRunUtil.runTaskForLink(tasks,taskCallBack1);
    }

    @Override
    public void setStop(boolean stop) {
        super.setStop(stop);
        if (stop){
            TaskRunUtil.stopTasks(tasks);
        }
    }
}
